package com.studio5704website.infrastructure.service;

import com.studio5704website.application.data.RoleWithToken;
import com.studio5704website.core.user.RoleWithTokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.Optional;

/**
 * @author 高威
 * 从redis查找已经登录的角色权限
 */
@Component
public class RedisRoleWithTokenService implements RoleWithTokenService {
    private RedisUtil redisUtil;

    @Autowired
    public RedisRoleWithTokenService(RedisUtil redisUtil) {
        this.redisUtil = redisUtil;
    }

    @Override
    public Optional<RoleWithToken> getRoleWithToken(String id) {
        String tokenPermission = (String) redisUtil.get(id);
        if (tokenPermission != null) {
            String[] list = tokenPermission.split(" ");
            if (list.length < 2) {
                return Optional.empty();
            }
            String token = list[0];
            String permission = list[1];
            return Optional.ofNullable(new
                    RoleWithToken(id, token, permission, redisUtil.getExpire(id)));
        } else {
            return Optional.empty();
        }
    }

    @Override
    public boolean setRoleWithToken(RoleWithToken roleWithToken) {
        String id = roleWithToken.getId();
        String token = roleWithToken.getToken();
        String permission = roleWithToken.getPermission();
        String tokenPermission = token + " " + permission;
        return redisUtil.set(id, tokenPermission, roleWithToken.getDueTime());
    }

    @Override
    public void deleteLoginRole(String id) {
        redisUtil.del(id);
    }
}
